<?php

namespace app\api\controller;

use Exception;
use think\Cache;
use think\Controller;
use think\Log;
use think\Request;

/**
 * 龙宫传奇专用
 */
class Legend extends Controller
{
    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
        // parent::__construct();
        // set_cors();
    }

    //openid
    public function w_code()
    {
        try {
            $params = Request::instance()->param();
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx7a82ee3ed7482fb5&secret=a38f72e2daf57349516e575677839c89&js_code=' . $params['code'] . '&grant_type=authorization_code';
            $res = file_get_contents($url);
            exit($res);
        } catch (\Exception $e) {
        }
    }
    public function user_info()
    {
        $params = Request::instance()->param();
        mylog($params);
        $user_info = db('user_info', 'db_operatelog_long_data')->where(['user_id' => $params['user_id'],'key'=>$params['key']])->find();
        if (empty($user_info)) {
            db('user_info', 'db_operatelog_long_data')->insert([
                'user_id' => $params['user_id'],
                'key' => $params['key'],
                'content' => $params['content'],
            ]);
        }else{
            db('user_info', 'db_operatelog_long_data')->where(['user_id' => $params['user_id'],'key'=>$params['key']])->update([
                'content' => $params['content'],
            ]);
        }
        exit(json_encode(['code' => 200, 'msg' => 'ok']));
    }
    public function get_user_info()
    {
        $params = Request::instance()->param();        
        $user_info = db('user_info', 'db_operatelog_long_data')->where(['user_id' => $params['user_id'],'key'=>$params['key']])->find();
        exit(json_encode(['code' => 200, 'msg' => 'ok','data'=>$user_info,'time'=>time()]));
    }

    public function scheme()
    {
        $params = Request::instance()->param();
        mylog($params);
        $sign = $this->sign($params['nonce'], $params['timestamp']);
        if ($sign != $params['signature']) {
            $obj = [
                'code' => 40004,
                'url_scheme' => ''
            ];
            exit(json_encode($obj));
        }
        $res = $this->token();
        $data = json_decode($res, true);
        $token = $data['access_token'];
        $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $token;
        $res  = json_decode($this->request_by_curl($url), true);
        $obj = [
            'code' => 0,
            'url_scheme' => $res['openlink']
        ];
        exit(json_encode($obj));
    }

    public function sign($nonce, $timestamp)
    {
        $token = '3D3DFD64226A7489C6664C5DB214DDDD';
        $collect = array((string)$token, (string)$nonce, (string)$timestamp);
        usort($collect, 'strcmp');
        $signature = sha1(implode('', $collect));
        return $signature;
    }
    public function token()
    {
        $token = Cache::get('wx-token-long');
        if (!empty($token)) {
            return $token;
        }
        $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7a82ee3ed7482fb5&secret=a38f72e2daf57349516e575677839c89');
        Cache::set('wx-token-long', $res, 5000);
        return $res;
    }

    function request_by_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, '');

        // 执行 cURL 请求
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
